<template>
	<view class="pages-dynamic" :style="{background:pageColor}">
		<block v-if="isLoad">
			<block v-if="configInfo.plugAuth.dynamic">
				<fixed>
					<!-- #ifndef H5 -->
					<uni-nav-bar :fixed="false" :shadow="false" :statusBar="true" :title="navTitle" color="#ffffff"
						:backgroundColor="primaryColor">
					</uni-nav-bar>
					<!-- #endif -->
					<view class="fix-info rel" :style="{background:pageColor}">
						<!-- #ifndef H5 -->
						<view class="space-top abs" :style="{background:primaryColor}"></view>
						<!-- #endif -->
						<view class="search-info fill-base pt-lg pl-lg pr-lg pb-md abs">
							<view class="flex-center pb-md">
								<view @tap.stop="$refs.show_item.open()"
									class="dynamic-btn flex-center f-caption mr-lg radius"
									:style="{color:primaryColor,border:`1rpx solid ${primaryColor}`}"
									v-if="coach_status == 1 && configInfo.web_coach_port">
									<i class="iconfont icon-jia-bold"></i>
									发动态
								</view>
								<view class="flex-1">
									<search @input="toSearch" type="input" :padding="0" :radius="30"
										backgroundColor="#F0F0F0" :placeholder="'请输入'+$t('action.attendantName')+'姓名'">
									</search>
								</view>
							</view>
							<tab @change="handerTabChange" :list="tabList" :activeIndex="activeIndex*1"
								:activeColor="primaryColor" width="50%" height="90rpx" fontSize="28rpx" :numberType="2"
								lineClass="sm"></tab>
						</view>
					</view>
				</fixed>

				<view class="space-md"></view>
				<wfalls-flow :list="list.data" :path="1" ref="dynamic_wfalls" v-if="list.data.length > 0"></wfalls-flow>
				<load-more :noMore="list.current_page>=list.last_page&&list.data.length>0" :loading="loading"
					v-if="loading">
				</load-more>

				<block v-if="!loading&&list.data.length<=0&&list.current_page==1">
					<!-- #ifdef H5 -->
					<abnor v-if="location.lat&&location.lng"
						:percent="`calc(100vh - 244rpx - calc(98rpx + env(safe-area-inset-bottom) / 2))`">
					</abnor>
					<!-- #endif -->
					<!-- #ifndef H5 -->
					<abnor v-if="location.lat&&location.lng"
						:percent="`calc(100vh - 420rpx - calc(98rpx + env(safe-area-inset-bottom) / 2))`">
					</abnor>
					<!-- #endif -->
					<block v-if="!location.lat&&!location.lng">
						<!-- #ifdef H5 -->
						<abnor type="NOT_LOCATION" title="暂无数据"
							percent="calc(100vh - 244rpx - calc(98rpx + env(safe-area-inset-bottom) / 2))"></abnor>
						<!-- #endif -->
						<!-- #ifndef H5 -->
						<abnor type="NOT_LOCATION" title="暂无数据" @confirm="toOpenLocation"
							percent="calc(100vh - 420rpx - calc(98rpx + env(safe-area-inset-bottom) / 2))"
							:button="[{ text: '开启定位' , type: 'confirm' }]" btnSize=""></abnor>
						<!-- #endif -->
					</block>
				</block>
				<block v-else>
					<view class="space-footer"></view>
					<view :style="{height: `${configInfo.tabbarHeight}px`}"></view>
				</block>

			</block>
			<block v-else>
				<abnor type="NOT_AUTH" :isCenter="true"></abnor>
			</block>


			<longbingbing-tabbar :cur="3"></longbingbing-tabbar>



			<uni-popup ref="show_item" type="bottom">
				<view class="show-popup pd-lg">
					<view @tap.stop="toAddDynamic(1)" class="show-item flex-center f-paragraph mt-md radius-16">发布图片
					</view>
					<view @tap.stop="toAddDynamic(2)" class="show-item flex-center f-paragraph mt-md radius-16">发布视频
					</view>
					<view @tap.stop="$refs.show_item.close()" class="show-item flex-center f-paragraph mt-md radius-16"
						:style="{color:primaryColor}">取消</view>
					<view class="space-safe"></view>
				</view>
			</uni-popup>


			<!-- #ifdef APP-PLUS -->
			<longbingbing-open-location-info ref="open_location_info"></longbingbing-open-location-info>
			<longbingbing-login-info></longbingbing-login-info>
			<longbingbing-app-check-auth type="location" ref="app_check_item"
				@confirm="toConfirmOpenLoca"></longbingbing-app-check-auth>
			<!-- #endif -->
			<longbingbing-change-user-type></longbingbing-change-user-type>
		</block>

		<!-- #ifdef MP-WEIXIN -->
		<user-privacy ref="user_privacy" :show="false"></user-privacy>
		<!-- #endif -->
	</view>
</template>

<script>
	import {
		mapState,
		mapActions,
		mapMutations
	} from "vuex"
	import siteInfo from '@/siteinfo.js';
	import wfallsFlow from "@/components/wfalls-flow.vue"
	export default {
		components: {
			wfallsFlow
		},
		data() {
			return {
				isLoad: false,
				options: {},
				navTitle: '',
				loading: true,
				lockTap: false
			}
		},
		computed: mapState({
			pageActive: state => state.dynamic.pageActive,
			haveOperItem: state => state.dynamic.haveOperItem,
			activeIndex: state => state.dynamic.activeIndex,
			tabList: state => state.dynamic.tabList,
			param: state => state.dynamic.param,
			list: state => state.dynamic.list,
			coach_status: state => state.dynamic.coach_status,
			configInfo: state => state.config.configInfo,
			isGzhLogin: state => state.user.isGzhLogin,
			haveShieldOper: state => state.user.haveShieldOper
		}),
		async onLoad(options) {
			let launch = 0
			// #ifdef MP-WEIXIN 
			let {
				scene
			} = await uni.getLaunchOptionsSync()
			launch = scene // 1154：朋友圈
			options.launch = launch
			// #endif
			options = await this.updateCommonOptions(options)
			let {
				pid = 0,
			} = options
			options.pid = pid * 1
			this.options = options

			// #ifdef MP-WEIXIN
			uni.showShareMenu({
				menus: ['shareAppMessage', 'shareTimeline']
			})
			// #endif
			
			if (this.pageActive && !pid) {
				this.isLoad = true
				this.loading = false
				this.$util.hideAll()
				this.initNavTitle()
				return
			}

			await this.initIndex()
			this.updateDynamicItem({
				key: 'pageActive',
				val: true
			})
			this.initNavTitle()
		},
		async onShow() {
			this.initNavTitle(this.appShare ? 0 : 1)
			if (this.haveOperItem) {
				this.initRefresh()
				this.updateDynamicItem({
					key: 'haveOperItem',
					val: false
				})
			}

			if (!this.location.lat && this.locaRefuse) {
				this.toResetUtilLoca()
			}

			let {
				status: coach_status = 0,
				coach_position = 0
			} = this.userCoachStatus
			let {
				realtime_location = 0
			} = this.configInfo

			if (this.haveShieldOper == 1) {
				await this.initIndex()
				this.updateUserItem({
					key: 'haveShieldOper',
					val: 0
				})
			} else if (this.pageActive && !realtime_location && coach_position && coach_status == 2) {
				this.$util.getCoachUtilLoca()
			}

		},
		async onPullDownRefresh() {
			// #ifndef APP-PLUS
			uni.showNavigationBarLoading()
			// #endif
			await this.initRefresh();
			uni.stopPullDownRefresh()
		},
		async onReachBottom() {
			if (this.list.current_page >= this.list.last_page || this.loading) return;
			this.param.page = this.param.page + 1;
			this.loading = true;
			await this.getList();
			setTimeout(() => {
				this.$refs.dynamic_wfalls.handleViewRender();
			}, 0)
		},
		onShareTimeline() {
			let {
				navTitle: title
			} = this
			let {
				app_logo
			} = this.configInfo
			let imageUrl = app_logo || ''
			let {
				id: pid = 0
			} = this.userInfo
			let query = `pid=${pid}`
			return {
				title,
				imageUrl,
				query
			}
		},
		onShareAppMessage(e) {
			let {
				navTitle: title
			} = this
			let {
				id: pid = 0
			} = this.userInfo
			let path = `/pages/dynamic?pid=${pid}`
			this.$util.log(path)
			return {
				title,
				imageUrl: '',
				path,
			}
		},
		watch: {
			locaRefuse(newval, oldval) {
				if (!newval) {
					this.toResetUtilLoca()
				}
			}
			// #ifndef H5
			,
			changeOnAddr(newval, oldval) {
				let {
					noloca,
				} = this.noChangeLoca
				if (newval && noloca) {
					this.initUtilLocaData()
				}
			},
			noChangeLoca(newval, oldval) {
				setTimeout(() => {
					let {
						lat,
						lng,
						unix = 0
					} = this.changeOnAddr
					let {
						noloca
					} = this.noChangeLoca
					let cur_unix = this.$util.DateToUnix(this.$util.formatTime(new Date(), 'YY-M-D h:m:s'))
					if (noloca && ((!lat && !lng) || !unix || (unix && (cur_unix - unix >= 1)))) {
						this.getUtilLocation()
					}
				}, 800)
			}
			// #endif
		},
		methods: {
			...mapActions(['getConfigInfo', 'getUserInfo', 'getDynamicIndex',
				'getDynamicList', 'addScanRecord', 'updateScanRecord', 'updateCommonOptions'
			]),
			...mapMutations(['updateUserItem', 'updateServiceItem', 'updateTechnicianItem', 'updateMapItem',
				'updateDynamicItem', 'updateShopstoreItem'
			]),
			async initIndex(refresh = false) {
				let {
					pid = 0,
					launch=0
				} = this.options

				let code = this.scanRecordId
				// #ifdef H5
				code = this.$util.getQueryString('code')
				// #endif 
				if (pid && !code) {
					this.addScanRecord({
						type: 2,
						qr_id: pid,
						is_qr: 0
					})
				}

				let {
					id: uid = 0
				} = this.userInfo
				if (!this.configInfo.id || refresh || (pid && code && !uid)) {
					await this.getConfigInfo()
				}
				if (launch != 1154 && pid && !code && !uid) {
					await this.getUserInfo()
				}
				let {
					dynamic = false
				} = this.configInfo.plugAuth
				if (!dynamic) {
					this.isLoad = true
					this.loading = false
					this.$util.hideAll()
					return
				}
				await this.getDynamicIndex()
				this.isNotLoca()
			},
			async initRefresh() {
				await this.initIndex(true)
			},
			async initNavTitle(isShow = 0) {
				this.$util.setNavigationBarColor({
					bg: this.primaryColor
				})
				let {
					tabBar
				} = this.configInfo
				if (tabBar && tabBar.length > 0) {
					let ind = tabBar.findIndex(item => {
						return item.id == 3
					})
					let navTitle = ind == -1 ? '动态' : tabBar[ind].name
					this.navTitle = navTitle
					// #ifdef H5
					uni.setNavigationBarTitle({
						title: navTitle
					})
					// #endif
					if (this.scanRecordId) {
						this.updateScanRecord()
					}
					if (!isShow) {
						// #ifdef H5
						this.$jweixin.initJssdk(() => {
							this.toAppShare()
						})
						this.updateUserItem({
							key: 'appShare',
							val: false
						})
						// #endif
					}
				}
			},
			async toResetUtilLoca() {
				// #ifdef APP-PLUS
				let {
					lat: locaLat = 0
				} = this.location
				let {
					appCheckLocaStatus = null
				} = this
				if (!locaLat && appCheckLocaStatus == 1 && this.pageActive) {
					let {
						lng = 0,
							lat = 0
					} = await this.$util.getUtilLocation()
					if (!lat && !lng) return
					this.$refs.open_location_info.pShow = false
					await this.getList(1)
					let updateArr = ['updateServiceItem', 'updateTechnicianItem',
						'updateMapItem',
						'updateShopstoreItem'
					]
					updateArr.map(item => {
						this[item]({
							key: 'pageActive',
							val: false
						})
					})
				}
				// #endif
			},
			async toOpenLocation() {
				// #ifdef APP-PLUS
				if (plus.os.name == 'Android' && plus.navigator.checkPermission(
						'android.permission.ACCESS_FINE_LOCATION') ===
					'undetermined') {
					this.$refs.app_check_item.open()
				} else {
					this.toConfirmOpenLoca()
				}
				// #endif
				// #ifndef APP-PLUS
				this.toConfirmOpenLoca()
				// #endif
			},
			async toConfirmOpenLoca() {
				// #ifdef MP-WEIXIN
				let privacyCheck = this.$refs.user_privacy.check()
				if (privacyCheck) {
					this.$refs.user_privacy.open()
					return
				}
				// #endif
				this.initRefresh()
			},
			toAppShare() {
				let {
					id: pid = 0
				} = this.userInfo
				let {
					navTitle: title
				} = this
				let {
					siteroot
				} = siteInfo
				let url = siteroot.split('/index.php')[0]
				let href = `${url}/h5/#/pages/dynamic?pid=${pid}`
				let {
					app_logo
				} = this.configInfo
				let imageUrl = app_logo || ''
				this.$jweixin.showOptionMenu()
				this.$jweixin.shareAppMessage(title, '', href, imageUrl)
				this.$jweixin.shareTimelineMessage(title, href, imageUrl)
			},
			async handerTabChange(index) {
				this.updateDynamicItem({
					key: 'activeIndex',
					val: index
				})
				uni.pageScrollTo({
					scrollTop: 0
				})
				if (index == 1) {
					await this.getDynamicIndex()
				}
				await this.getList(1)
			},
			async isNotLoca() {
				let {
					location,
					locaRefuse
				} = this

				let {
					status: coach_status = 0,
					coach_position = 0
				} = this.userCoachStatus



				// #ifdef H5
				if (coach_position && coach_status == 2 && (location.lat && location.address != '暂未获取到位置信息')) {
					this.updateUserItem({
						key: 'isChangeCoachLoca',
						val: true
					})
				}
				// #endif


				// #ifdef APP-PLUS
				if (!locaRefuse && (!location.lat || (location.lat && location.address ==
						'暂未获取到位置信息'))) {
					// #endif
					// #ifndef APP-PLUS
					if (!location.lat || (location.lat && location.address ==
							'暂未获取到位置信息')) {
						// #endif

						// #ifdef MP-WEIXIN
						let privacyCheck = this.$refs.user_privacy.check()
						if (privacyCheck || typeof(privacyCheck) == 'string') {
							if (privacyCheck) {
								this.$refs.user_privacy.open()
							}
							this.isLoad = true
							this.loading = false
							this.$util.hideAll()
							return
						}
						// #endif
						// #ifndef H5
						if (coach_position && coach_status == 2) {
							let {
								lat: change_lat = 0,
								lng: change_lng = 0,
								unix = 0
							} = this.changeOnAddr
							let cur_unix = this.$util.DateToUnix(this.$util.formatTime(
								new Date(), 'YY-M-D h:m:s'))
							let noloca = change_lat && change_lng && (unix && (cur_unix -
								unix < 3)) ? false : true
							if (!noloca) {
								let loca = Object.assign({}, this.location, {
									lat: change_lat,
									lng: change_lng,
									is_util_loca: 1
								})
								this.updateUserItem({
									key: 'location',
									val: loca
								})
							}
							this.updateUserItem({
								key: 'noChangeLoca',
								val: {
									noloca
								}
							})
							if (this.noChangeLoca.noloca) return
							this.initUtilLocaData()
						} else {
							this.getUtilLocation()
						}
						this.updateMapItem({
							key: 'pageActive',
							val: false
						})
						return
						// #endif

						// #ifdef H5
						await this.$util.getUtilLocation()
						this.updateMapItem({
							key: 'pageActive',
							val: false
						})
						// #endif
					}
					this.initUtilLocaData()
				},
				async getUtilLocation() {
						await this.$util.getUtilLocation()
						this.initUtilLocaData()
					},
					async initUtilLocaData() {
							// #ifndef H5
							this.updateUserItem({
								key: 'noChangeLoca',
								val: {
									noloca: false
								}
							})
							// #endif 
							await this.getList(1)
							let {
								lat = 0, lng = 0, is_util_loca = 0, isIp = true
							} = this.location
							if (lat && lng && is_util_loca) {
								this.$util.getMapInfo(isIp)
							}
						},
						toSearch(val) {
							this.param.coach_name = val
							this.getList(1)
						},
						async getList(page) {
								if (page) {
									this.param.page = 1
									this.updateDynamicItem({
										key: 'list',
										val: {
											data: [],
											last_page: 1,
											current_page: 1
										}
									})
								}
								let {
									lat = 0, lng = 0
								} = this.location

								// #ifdef APP-PLUS
								if (!lat && !lng) {
									this.updateDynamicItem({
										key: 'list',
										val: {
											data: [],
											last_page: 1,
											current_page: 1
										}
									})
									this.isLoad = true
									this.loading = false
									this.$util.hideAll()
									return
								}
								// #endif
								let {
									list: oldList,
								} = this
								let param = Object.assign({}, this.param, {
									lat,
									lng
								});
								await this.getDynamicList(param)
								this.isLoad = true
								this.loading = false
								this.$util.hideAll()
							},
							toAddDynamic(type) {
								this.$refs.show_item.close()
								this.$util.goUrl({
									url: `/dynamic/pages/technician/edit?type=${type}`
								})
							}
			}
		}
</script>


<style lang="scss">
	.pages-dynamic {
		.fix-info {
			height: 225rpx;

			.space-top {
				width: 100%;
				height: 40rpx;
				top: 0;
			}

			.search-info {
				width: 100%;
				top: 0;
				border-radius: 40rpx;

				.dynamic-btn {
					width: 134rpx;
					height: 56rpx;
					transform: rotateZ(360deg);

					.iconfont {
						font-size: 24rpx;
						margin-right: 6rpx;
					}
				}
			}
		}

		.show-popup {
			width: 750rpx;
			background: #F3F3F5;
			border-radius: 30rpx 30rpx 0 0;

			.avatar {
				width: 84rpx;
				height: 84rpx;
			}

			.show-item {
				color: #222;
				height: 100rpx;
				background: #fff;
			}
		}

	}
</style>